[英]Flutter - Autoscroll to a specific Card
我正在嘗試啟用自動滾動到它應該以垂直方式滾動的特定卡片,我使用 Scrollable.ensureVisible 實現了這一點。 但它只有在 Scrollable.ensureVisible 放置在 ontap 或任何小部件的 onpressed function 時才有效(使用按鈕點擊嘗試)。 但我的實際要求是,Autoscroll 應該在沒有任何用戶操作的情況下工作。 我嘗試了以下代碼,但出現了錯誤鍵。CurrentContext is null
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:html/parser.dart';
void main() {
runApp(TestClass());
}
class TestClass extends StatefulWidget {
@override
_TestClassState createState() => _TestClassState();
}
class _TestClassState extends State<TestClass> {
bool loading = true;
final scrollCardOne = new GlobalKey();
final scrollCardTwo = new GlobalKey();
var ScrolltoCard1,
ScrolltoCard2,
response;
Future fetchData() async {
ScrolltoCard1= 'no';
ScrolltoCard2= 'yes';
final response = await http.get(URL);
if (response.statusCode == 200) {
print("Fetch successful");
response = response.body;
} else {
print(response.statusCode);
}
}
@override
void initState() {
super.initState();
this.fetchData().then((value) {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
if (ScrolltoCard1 == 'yes') {
Scrollable.ensureVisible(disclaimer.currentContext);
} else if (ScrolltoCard2 == 'yes') {
Scrollable.ensureVisible(greivance.currentContext);
return MaterialApp(
home: Scaffold(
body: Container(
child: Column(
children: <Widget>[
SizedBox(
height: 100.0,
),
Text(
'Text Heading',
),
),
Expanded(
child: Card(
margin: EdgeInsets.all(10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 2,
color: Colors.white,
child: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
SizedBox(
key: ScrolltoCard1,
height: 30.0,
),
aboutCardOne(),
SizedBox(
key: ScrolltoCard2,
height: 30.0,
),
aboutCard2(),
],
),
),
),
),
),
],
),
),
),
);
}
Widget aboutCardOne() {
return Card(
margin: EdgeInsets.all(10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
Text(
"Card1 Sample"
),
Text(
'Sample Text 1')
])),
),
],
),
);
}
Widget aboutCardTwo() {
return Card(
margin: EdgeInsets.all(10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
Text(
"Card2 Sample"
),
Text(
'Sample Text 2')
])),
),
],
),
);
}
}
如果您將 ListView 與此 package scroll_to_index 一起使用,只需創建 2 個列表項並滾動到您想要的那個?
列表視圖項目:
AutoScrollTag(
key: ValueKey(index),
controller: controller,
index: index,
child: child
)
controller.scrollToIndex(index, preferPosition: AutoScrollPosition.begin)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.