【问题标题】:How to add programmatically List Widgets to TabBar?如何以编程方式将列表小部件添加到 TabBar?
【发布时间】:2019-04-17 17:39:32
【问题描述】:

我正在构建一个应用程序,该应用程序连接并向 HTTP 服务器发送请求,并在获得响应时将它们解析为 JSON 对象并显示输出。 当我使用以下方法时会出现问题:

Future<List<Widget>> getPizzas() async {
    List<Widget> pizzasElements;
    await PizzeriaAPI().getMenu().then((response) {
      Iterable list = json.decode(response.body);
      var pizzas = list.map((model) => Pizza.fromJson(model)).toList();
      pizzasElements =new List<Widget>.generate(pizzas.length, (int index){
        Row row = new Row();
        row.children.add(new Text(pizzas[index].name));
        row.children.add(new Text("${pizzas[index].price} \$"));
        row.children.add(new MaterialButton(color: Colors.green,child: Text("Add"),onPressed: (){
          // esegui il post
        }));
        return row;
      });
    });
  }

这是构建方法:

@override
  Widget build(BuildContext context) {
    getPizzas().then((List<Widget> response){
      return MaterialApp(
          theme: ThemeData(
            primarySwatch: Colors.blue,
            brightness: Brightness.dark,
          ),
          home: DefaultTabController(length: 4, child: Scaffold(
            appBar: AppBar(
              title: const Text('Pizzeria'),
              bottom: TabBar(
                  isScrollable: true,
                  tabs: [
                    Tab(text: "Buy"),
                    Tab(text: "Orders"),
                    Tab(icon: Icon(Icons.shopping_cart)),
                    Tab(icon: Icon(Icons.settings))
                  ]
              ),
            ),
            body: TabBarView(children: [
              Column(
                children: response,
              ),
              Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Text("Orders")
                    ],
                  )
                ],
              ),
              Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Icon(Icons.shopping_cart)
                    ],
                  )
                ],
              ),
              Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Icon(Icons.settings)
                    ],
                  )
                ],
              )
            ]),
          )
          )
      );
    }
    );
  }
}

我获得的是未来对象而不是列表对象。
用于显示元素的代码是:

Column(
      children: response,
),

如何从这个方法中获取 List 并显示输出?

【问题讨论】:

    标签: android dart flutter android-asynctask futuretask


    【解决方案1】:

    问题在于getPizzas() 是异步的,这意味着它返回一个Future。您需要的本质上意味着您应该将渲染代码更改为:

    Column(
      children: pizzasElements,
    ),
    
    

    因为您似乎将pizzaElements 设置为包含您的小部件列表。

    更新:

    您需要做的是将构建方法与请求分开。因此,在您的构建函数中,只需调用 getPizzas() 函数并忘记它。像这样:

    Widget build(BuildContext context) {
        getPizzas();
        return MaterialApp(...
    

    接下来,您需要确保 pizzaElements 已初始化并且是类属性而不是局部变量。因此,这意味着您需要使用 StatefulWidget,而这将发生在 State 类中。

    List<Widget> pizzaElements = <Widget>[];
    

    然后在getPizzas() 中,您需要确保调用setState 以使您的小部件与列表一起重新呈现:

    void getPizzas() {
      PizzeriaAPI().getMenu().then((response) {
        Iterable list = json.decode(response.body);
        var pizzas = list.map((model) => Pizza.fromJson(model)).toList();
        setState(() {
          pizzasElements = new List<Widget>.generate(pizzas.length, (int index) {
            Row row = new Row();
            row.children.add(new Text(pizzas[index].name));
            row.children.add(new Text("${pizzas[index].price} \$"));
            row.children.add(new MaterialButton(
                color: Colors.green,
                child: Text("Add"),
                onPressed: () {
                  // esegui il post
                }));
            return row;
          });
        });
      });
    }
    

    【讨论】:

    • 问题依然存在,因为如何在 build 方法中使用 getPizzas() 方法同步设置 PizzasElements?
    • 我明白了。编辑我的答案。
    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多