如何将setstate作为参数传递给类方法

时间:2019-07-13 07:45:48

标签: flutter dart callback setstate

在波动中,我使用一个类从数据库加载开关小部件的值,然后在切换开关时更新该数据库。我以某种方式需要在实例的调用函数上使用该类调用setstate,但是它似乎不起作用。 有关示例,请参见下面的代码。

  • 第一个开关是我如何在没有数据库类的情况下编写它。这很好,当点击开关时,它都移动并且打印显示值已更改。

  • 但是,在第二个开关小部件中,我使用数据库类来构建它,但是它似乎没有正确调用回调函数。打印件始终打印为假。

我以为我尝试了=>和(){}的所有组合,但仍然有些不妥。我很确定问题是在该行中如何处理回调:callBackFunctionForSetState(); 也许应该使用callBackFunctionForSetState((){})来调用它;但这也不起作用。

import 'package:flutter/material.dart';

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

bool myBool = true;

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      home: ScreenUpgrades(),
    );
  }
}

class ScreenUpgrades extends StatefulWidget {
  @override
  _ScreenUpgradesState createState() => _ScreenUpgradesState();
}

class _ScreenUpgradesState extends State<ScreenUpgrades> {
  @override
  Widget build(BuildContext ctxt) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Upgrades"),
        ),
        body: FutureBuilder(
            future: buildSwitchList(),
            builder: (BuildContext ctxt, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                return ListView(children: snapshot.data);
              } else {
                return Center(child: CircularProgressIndicator());
              }
            }));
  }
  Future<List> buildSwitchList() async {
    List<Widget> widgetList = [];
    //This one below for a working example only
    widgetList.add(Switch(value: myBool,onChanged: (bb)=>nonDBSetState()));

    //Normally I'll create a bunch of widgets by loading their data from the DB as below
    widgetList.add(DataBaseSwitchBuilder(1,()=>setState((){})).listViewWidget);
    return widgetList;
  }
  nonDBSetState()
  {
    myBool = !myBool;
    print('New value of first switch: ' + myBool.toString());
    setState((){});
  }
}

class DataBaseSwitchBuilder {
  Widget listViewWidget;
  int dbID;
  bool onOff;
  Function callBackFunctionForSetState;
  DataBaseSwitchBuilder (int paramID, Function callBack)
  {
    dbID=paramID; //used to query the parameter from the DB
    onOff = true;
    callBackFunctionForSetState=callBack;
    listViewWidget=(Switch(value: onOff,onChanged: (bb)=> updateDBAndState()));
  }
  updateDBAndState()
  {
    //update the switch
    onOff = !onOff;
    print('DB Swtich value now: ' + onOff.toString());
    //first we save the record in the DB
        //todo: code for updating DB
    //Then call the passed function which should be a setstate from the calling function
    //Below doesn't seem to work.
    callBackFunctionForSetState();
  }
}

我只是期望updateDBAndState允许我将开关的新值保存到数据库,然后调用setstate回调。

0 个答案:

没有答案