我有一个非常简单的Ffltter应用程序,TabBarView有两个视图(Tab 1和Tab 2),其中一个(Tab 1)有一个包含许多简单文本小部件的ListView,问题是在我向下滚动Tab 1的ListView元素后,如果我从Tab 1滑动到Tab 2,最后从 Tab 2到Tab 1,ListView中Tab 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: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late TabController controller;
@override
void initState() {
super.initState();
controller = TabController(
length: 2,
vsync: this,
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
var tabs = const <Tab>[
Tab(icon: Icon(Icons.home), text: 'Tab 1'),
Tab(icon: Icon(Icons.account_box), text: 'Tab 2')
];
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: TabBarView(controller: controller, children: <Widget>[
ListView(children: <Widget>[
Column(children: <Widget>[
for (int i = 0; i < 48; i++) Text('Data $i'),
])
]),
const Center(child: Text('Tab 2'))
]),
bottomNavigationBar: Material(
color: Colors.deepOrange,
child: TabBar(controller: controller, tabs: tabs),
),
);
}
}
我甚至在另一个类中将TabBarViewchildrens(表1和表2)分开,我注意到
@override
Widget build(BuildContext context) {
...
}
方法(Tab 1和Tab 2),每次我滑动到它的容器选项卡时都会执行.
我的问题是:
1.- How can I keep the scroll of the ListView even if I move from tab to tab?个
2.- Is there a way to execute the
@override
Widget build(BuildContext context) {
}
method only once if I separate the TabBarView childrens (Tab 1 and Tab 2) to another classes?个 我的意思是,如果我必须在创建Tab 1和Tab 2时检索数据,我不想在每次滑动Tab时都这样做.那会很贵的.
3.- In general, Is there a way to prevent that a tab view (including it's variables, data, etc.) be rebuilt every time I swipe to that tab?个
Thank you in advance.个