颤振为什么我的小部件条件检查不起作用

时间:2019-09-15 09:10:12

标签: flutter dart

我在main.dart(我的第一个应用级别页面)中有此标签:

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

class MaterialAppContainer extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MaterialAppContainerState();
  }
}

class _MaterialAppContainerState extends State<MaterialAppContainer> {
  ...
  globalValues.showLoadingBar ? _buildLoadingBar() : Container()
  ...
}

但是,在我的下级组件之一(testpage.dart)中,我想控制此加载栏是否显示,因此想法是在通话开始时将加载栏置于打开状态并停止之后。像这样:

(doWhatever).then((_) {
  setState(() {
    globalValues.showLoadingBar = false;
    print(globalValues.showLoadingBar);
  });
});

可以正确打印更改,但是加载栏不会消失。我尝试在testpage.dart上添加更改,并且可以正确切换:

globalValues.showLoadingBar ? Text('True') : Text('False')

有人可以帮助我了解我在做什么,我显然缺少有关颤振/飞镖的组件/状态控制的东西。

2 个答案:

答案 0 :(得分:0)

我在类之外移动了loadingInProgress来模拟全局变量。
并使用future.delayed模拟作业执行

代码段

Future _loadData() async {
    await new Future.delayed(new Duration(seconds: 3));
  }

  void _incrementCounter() {
    setState(() {
      loadingInProgress = true;
    });

    _loadData().then((_) {
      setState(() {
        loadingInProgress = false;
      });
    });
  }

完整代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

bool loadingInProgress = false;

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  Future _loadData() async {
    await new Future.delayed(new Duration(seconds: 3));
  }

  void _incrementCounter() {
    setState(() {
      loadingInProgress = true;
    });

    _loadData().then((_) {
      setState(() {
        loadingInProgress = false;
      });
    });
  }

  Widget _buildBody() {
    if (loadingInProgress) {
      return new Center(
        child: new CircularProgressIndicator(),
      );
    } else {
      return new Center(
        child: new Text('Data loaded'),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

enter image description here

答案 1 :(得分:0)

我可以解决的最好想法(这个想法来自Shababb Karim的评论!),所以创建一个空的setState()函数,然后在可以使用它的全局位置引用它。这是一个示例:

您的家庭/主要组成部分

  reloadMainPageState() {
    setState(() {
      // This just reloads this component, you leave it empty like this
    });
  }

  @override
  void initState() {
    globalValues.reloadMainPageState = reloadMainPageState;
    super.initState();
  }

  Widget _buildLoadingBar() {
    if (globalValues.boolShowLoadingAnimation == false) return Container();

    // Here you can return whatever component you want
    return Container(
      color: Colors.black.withOpacity(0.4),
      child: Center(
        child: Loading(indicator: BallPulseIndicator(), size: 100.0),
      ),
    );
  }

您希望影响加载栏的任何其他组件:

  globalValues.boolShowLoadingAnimation = true;
  globalValues.reloadMainPageState();

  // ...load your data (which takes a while)

  globalValues.boolShowLoadingAnimation = false;
  globalValues.reloadMainPageState();

我希望这会有所帮助:)