将小工具拆分为较小的小工具

时间:2019-11-18 21:10:49

标签: flutter flutter-layout flutter-provider

我有一个包含3个不同部分的大部件(请参阅代码中的注释)。

问题: 当状态更改时,如何用较少的重建将窗口小部件分成3个部分?

provider documentation开始,我想我应该使用Consumer / Selector,但是示例对我来说太简洁了。

import 'package:flutter/material.dart';
import 'package:flutter_app/models/cultivator.dart';
import 'package:flutter_app/models/incarnation.dart';
import 'package:provider/provider.dart';

class CultivatorComponent  extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final cultivator = Provider.of<Cultivator>(context);
    return Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              // Part 1: only need Cultivator.Name
              Text('Cultivator ${cultivator.name} is here'),

              // Part 2: only need Cultivator.Incarnations
              ListView.builder(
                shrinkWrap: true,
                itemCount: cultivator.incarnations.length,
                itemBuilder: (context, index) {
                  return Container(
                    height: 50,
                    color: Colors.amber[500],
                    child: Center(child: Text('Incarnation ${cultivator.incarnations[index].name} is here')),
                  );
                },),

              // Part 3: only need number of Cultivator.Incarnations
              if(cultivator.canCreateIncarnation())
                RaisedButton.icon(
                    onPressed: () {
                      var newIncarnation = Incarnation();
                      cultivator.addIncarnation(newIncarnation);
                    },
                    icon: Icon(Icons.add),
                    label: Text('add incarnation'))
            ]
        )
    );
  }
}

感谢您的时间

0 个答案:

没有答案