我正在我的 Flutter 应用程序上创建一个返回顶部按钮,但它不起作用。这是按钮的 Dart 文件:
import 'package:flutter/material.dart';
import 'package:flutter_app/Widgets/GlobalWidgets/SelectionButton.dart';
class ToTheTopButton extends StatefulWidget {
@override
_ToTheTopButtonState createState() => _ToTheTopButtonState();
}
class _ToTheTopButtonState extends State<ToTheTopButton> with TickerProviderStateMixin {
ScrollController _scrollController = ScrollController();
/*
@override
void dispose() {
_scrollController.dispose(); // dispose the controller
super.dispose();
}*/
// This function is triggered when the user presses the back-to-top button
void _scrollToTop() {
_scrollController.animateTo(0,
duration: Duration(seconds: 3), curve: Curves.linear);
}
@override
Widget build(BuildContext context) {
return SelectionButton(name: "To the top", onTap: _scrollToTop);
}
}
我在底部导航栏中实现了这个按钮,而底部导航栏在我的主页中实现。“SelectionButton”的代码如下:
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class SelectionButton extends StatelessWidget {
SelectionButton({required this.name, required this.onTap});
String name;
void Function() onTap;
@override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextButton(onPressed: onTap, child: Text(name, style: TextStyle(color: Colors.black)),),
),
);
}
}