使用 setStat 更新小部件和问题

Updating a widget and issue with setStat

我目前正在编写本教程,其中将变量“myVariable”从一个外部文件传输到另一个文件。 Link: https://dev.to/lucianojung/global-variable-access-in-flutter-3ijm

我修改了我的代码,使变量“myVariable”在 myservice.dart 文件中可用,它有效,但问题是我无法动态更新我的文本小部件“widget.myVariable”,它仅在我执行“热重新加载”时更新我认为我们应该添加一个 setStat,但尽管尝试了几次,但我不知道如何实现它。

感谢您的帮助

myservice.dart

import 'package:flutter/material.dart';
import 'main.dart';

class MyService extends StatefulWidget {
  //Passed 'myVariable' ///////////////////////////////////////////////////
  static final MyService _instance = MyService._internal();
  // passes the instantiation to the _instance object
  factory MyService() => _instance;
  //initialize variables in here
  MyService._internal() {
    _myVariable = 0;
  }
  int _myVariable;
  //short getter for my variable
  int get myVariable => _myVariable;
  //short setter for my variable
  set myVariable(int value) => myVariable = value;
  void incrementMyVariable() => _myVariable++;
  /////////////////////////////////////////////////////
  @override
  _MyServiceState createState() => _MyServiceState();
}

class _MyServiceState extends State<MyService> {

  /* i try this but no result
   _displayCounter() {
     setState(() {
       widget.myVariable;
     });
   }
*/
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      width: 250,
      height: 90,
      child: Text(
        // '${_displayCounter()}',
        '${widget.myVariable}',
      ),
    );
  }
}

main.dart

import 'package:flutter/material.dart';
import 'myservice.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Service Demo App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MyService _myService = MyService();
  _incrementCounter() {
    setState(() {
      _myService.incrementMyVariable();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            MyService(), //myservice.dart
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

当我们需要管理共享资源时,我们使用单例。 您可以阅读更多 here.

您在这里尝试的是将单例 class 用作 'widget'。

很明显,您正在尝试使用 myVariable。或许你可以制作一个单独的小部件来满足这个要求。

1 -> 编辑 main.dart :我将使用 _myService 对象并将其传递给 Service() 应该显示计数的地方。

children: <Widget>[ 
  Text( 
   'You have pushed the button this many times:',
  ),

 /* Now because of setState(), the build method will be called
    as many times as the counter increases, which will call
    Service() with the MyService instance below
  */ 

Service(_myService), //  ------ service_widget.dart 
]

2 -> 保持 myservice.dart 不变(如教程中给出的那样)。

3 -> service_widget.dart 将如下所示:

import 'package:flutter/material.dart';
import './myservice.dart';

class Service extends StatelessWidget {

final MyService myService; 
Service(this.myService); // making use of MyService instance

@override
Widget build(BuildContext context) {
  return Container(
    color: Colors.yellow,
    width: double.infinity,
    child: Text(
      '${myService.myVariable}', // Access myVariable here
       textAlign: TextAlign.center,
       style: TextStyle(
         fontSize: 25,
         fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}  

现在可以正常使用了!

虽然您可以在此处查看完整代码,但我强烈建议您多尝试一下。

  1. main.dart

  2. myservice.dart

  3. service_widget.dart