首页 > 解决方案 > Flutter:结合bottomSheet和bottomNavigationBar并调用setState的奇怪动画

问题描述

我在有状态的小部件中有一个带有bottomSheet 和bottomNavigationBar 的脚手架。在 bottomSheet 中,我计划添加按钮、调用 setState 并触发本地小部件树的重建。

问题是,调用 setState 或重建小部件时会发生奇怪的动画。底部工作表似乎来自底部导航栏顶部的底部。

有没有办法解决这个问题,这样在重建或调用 setState 时不会发生这个动画?

请看下面的代码。要观察行为,请运行代码并单击绿色底部表:

import 'package:flutter/material.dart';

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

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomSheet: MaterialButton(onPressed: () {
        setState(() {});
      }, child: Container(height: 50, color: Colors.green)),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

在复制/粘贴和运行上面的代码时,您应该能够重现我正在谈论的行为。

我不确定我在这里做错了什么,但这对我来说似乎很可疑。

标签: flutterbottom-sheetstatefulwidget

解决方案


推荐阅读