setState Flutter时,PageViewer中的小部件未更改

时间:2019-12-24 03:52:03

标签: flutter dart flutter-layout

我试图在pageviewer中更改我的小部件, 当我点击容器时。 但是容器没有改变颜色,我的打印功能正常工作。

这是我的PageViewer代码

PageView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  controller: _controller,
                  itemCount: _samplePages.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _samplePages[index % _samplePages.length];
                  },
                ),

这里是我的容器代码

Widget page2() {
Color containerColor = Colors.blue;
return Center(
  child: Padding(
    padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
    child: Container(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(15)),
      child: Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              setState(() {
                containerColor = Colors.red;
                print('changed');
              });
            },
            child: AnimatedContainer(
              width: 100,
              height: 100,
              color: containerColor,
              duration: Duration(seconds: 1),
            ),
          )
        ],
      ),
    ),
  ),
);

}

已更改已打印,但容器颜色仍为蓝色。 有人可以告诉我我的错误在哪里吗?

谢谢。

更新:

这是我的完整代码:

class _AddCustomerState extends State<AddCustomer> {


int currentPage = 1;

  Color containerColor = Colors.blue;
  bool isLoading = false;

  Widget page1() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Padding(
            padding: const EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Page 1')
               ],
            ),
          ),
        ),
      ),
    );
  }

  Widget page2() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Column(
            children: <Widget>[
              InkWell(
                onTap: () {
                  setState(() {
                    containerColor = Colors.red;
                    print('changed');
                  });
                },
                child: AnimatedContainer(
                  width: 100,
                  height: 100,
                  color: containerColor,
                  duration: Duration(seconds: 1),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget page3() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page4() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page5() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  List<Widget> _samplePages;

  @override
  void initState() {
    setState(() {
      _samplePages = [
              page1(),
              page2(),
              page3(),
              page4(),
              page5(),
            ];
    });
    super.initState();
  }

  final _controller = new PageController();
  static const _kDuration = const Duration(seconds: 1);
  static const _kCurve = Curves.ease;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: EdgeInsets.only(top: 50),
              child: Text(
                'ADD CUSTOMER',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
              height: 30,
            ),
            AnimatedContainer(
              duration: Duration(milliseconds: 700),
              width: 600,
              height: currentPage == 4 ? 600 : 450,
              child: isLoading
                  ? SpinKitCircle(
                      size: 30,
                      color: Colors.white,
                    )
                  : PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _controller,
                      itemCount: _samplePages.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _samplePages[index % _samplePages.length];
                      },
                    ),
            ),
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 25.0),
              child: Container(
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        setState(() {
                          if (currentPage > 1) {
                            currentPage--;
                          }
                        });
                        _controller.previousPage(
                            duration: _kDuration, curve: _kCurve);
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(
                          currentPage == 1 ? 'Back' : 'Prev',
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                        )),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        _controller.nextPage(
                            duration: _kDuration, curve: _kCurve);
                        setState(() {
                          if (currentPage < 5) {
                            currentPage++;
                          }
                        });
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(currentPage > 4 ? 'Confirm' : 'Next',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18))),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

您可以在下面复制粘贴运行完整代码
您需要StatefulBuilder

工作演示

enter image description here

代码段

 Widget page2() {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15)),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      containerColor = Colors.red;
                      print('changed');
                    });
                  },
                  child: AnimatedContainer(
                    width: 100,
                    height: 100,
                    color: containerColor,
                    duration: Duration(seconds: 1),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }

完整代码

import 'package:flutter/material.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: AddCustomer(),
    );
  }
}

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

  final String title;

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

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @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:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class AddCustomer extends StatefulWidget {
  @override
  _AddCustomerState createState() => _AddCustomerState();
}

class _AddCustomerState extends State<AddCustomer> {
  int currentPage = 1;

  Color containerColor = Colors.blue;
  bool isLoading = false;

  Widget page1() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Padding(
            padding: const EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[Text('Page 1')],
            ),
          ),
        ),
      ),
    );
  }

  Widget page2() {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15)),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      containerColor = Colors.red;
                      print('changed');
                    });
                  },
                  child: AnimatedContainer(
                    width: 100,
                    height: 100,
                    color: containerColor,
                    duration: Duration(seconds: 1),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget page3() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page4() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page5() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  List<Widget> _samplePages;

  @override
  void initState() {
    setState(() {
      _samplePages = [
        page1(),
        page2(),
        page3(),
        page4(),
        page5(),
      ];
    });
    super.initState();
  }

  final _controller = new PageController();
  static const _kDuration = const Duration(seconds: 1);
  static const _kCurve = Curves.ease;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: EdgeInsets.only(top: 50),
              child: Text(
                'ADD CUSTOMER',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
              height: 30,
            ),
            AnimatedContainer(
              duration: Duration(milliseconds: 700),
              width: 600,
              height: currentPage == 4 ? 600 : 450,
              child: isLoading
                  ? CircularProgressIndicator(
                      /* size: 30,
                color: Colors.white,*/
                      )
                  : PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _controller,
                      itemCount: _samplePages.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _samplePages[index % _samplePages.length];
                      },
                    ),
            ),
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 25.0),
              child: Container(
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        setState(() {
                          if (currentPage > 1) {
                            currentPage--;
                          }
                        });
                        _controller.previousPage(
                            duration: _kDuration, curve: _kCurve);
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(
                          currentPage == 1 ? 'Back' : 'Prev',
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                        )),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        _controller.nextPage(
                            duration: _kDuration, curve: _kCurve);
                        setState(() {
                          if (currentPage < 5) {
                            currentPage++;
                          }
                        });
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(currentPage > 4 ? 'Confirm' : 'Next',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18))),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

答案 1 :(得分:0)

选择此行: Color containerColor = Colors.blue; 中的 Widget page2() {

原因: 您调用setState-> setState调用build()->构建调用page2()-> page2()设置containerColor = Colors.blue.

因此,变量containerColor应该超出您的page2()