我花了很多时间研究这个问题。有类似的线程,但我不认为这是相同的情况,所以让我问你一个问题。
我想做的是在单击加号按钮时使用HookConsumerWidget中的TabController添加一个选项卡,并转到最后添加的选项卡。
但在启动时,当点击加号按钮时,我得到以下错误:
控制器的长度属性(0)与TabBar的tabs属性中存在的选项卡数(3)不匹配。
- 3是加号按钮被单击的次数。
控制器长度似乎未从零开始更改。
下面是代码:
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class SampleListNotifier extends StateNotifier<List<String>> {
SampleListNotifier() : super(<String>[]);
// 値の操作を行う
void createSample(String title) {
state = [...state, title];
}
}
final sampleListProvider = StateNotifierProvider<SampleListNotifier, List<String>>(
(ref) => SampleListNotifier(),
);
class CustomTabController extends HookConsumerWidget {
const CustomTabController({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final samples = ref.watch(sampleListProvider);
final controller = useTabController(initialLength: samples.length);
final index = useState(samples.length);
final key = GlobalKey();
controller.addListener(() {
index.value = controller.index;
});
return Scaffold(
appBar: AppBar(
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.add),
onPressed: () async {
const result = 'test';
if (result?.isNotEmpty ?? true) {
ref.read(sampleListProvider.notifier).createSample(result!);
controller.animateTo(samples.length-1);
}
}),
title: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TabBar(
onTap: (index) {},
controller: controller,
isScrollable: true,
tabs: samples
.map((String sample) => Tab(text: sample))
.toList(),
),
],
),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () async {
print('pressed!');
},
),
],
),
body: TabBarView(
key: key,
controller: controller,
children: samples
.map((String sample) =>
TabPage(key: UniqueKey() , title: sample))
.toList(),
),
);
}
}
class TabPage extends StatelessWidget {
const TabPage({required Key key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Center(
child: Text(title)
);
}
}
先谢了。
1条答案
按热度按时间e5nqia271#
在将新选项卡添加到列表中时,添加加载程序,即CircularProgressIndicator()而不是Tabbar和TabBarView。然后在加载程序停止后调用controller.animateTo(samples.length-1)