面试题答案
一键面试- Widget复用方法:
- 在Flutter中,可以通过将重复使用的界面元素封装成一个独立的Widget来实现复用。这样做不仅可以提高代码的可维护性,还能减少代码冗余。
- 抽取Widget示例:
假设我们有一个简单的按钮,在多个页面都需要使用。首先创建一个新的Dart文件,例如
custom_button.dart
。import 'package:flutter/material.dart'; class CustomButton extends StatelessWidget { final String text; final VoidCallback onPressed; const CustomButton({required this.text, required this.onPressed, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, child: Text(text), ); } }
- 在不同页面中调用示例:
- 在
home_page.dart
中调用:
import 'package:flutter/material.dart'; import 'custom_button.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Home Page'), ), body: Center( child: CustomButton( text: 'Click Me', onPressed: () { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Button Clicked')), ); }, ), ), ); } }
- 在
second_page.dart
中调用:
import 'package:flutter/material.dart'; import 'custom_button.dart'; class SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Page'), ), body: Center( child: CustomButton( text: 'Do Something', onPressed: () { Navigator.pop(context); }, ), ), ); } }
- 在