问题描述
我对Flutter相当陌生,并且用Dart语言写作。我正在尝试创建一个TextField,以在用户输入时更改颜色和fontfamily。到目前为止,我有一个可以创建新TextField的按钮。我有一个为字体创建的对话框。我只是不知道如何保存字体对话框中的用户输入并将其链接到TextField。
Here is a photo with the TextField
Here is where i can choose a font
问题是我不知道如何链接用户会选择实际更改文本字体的字体。
有人可以帮我吗!
这是我的代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() => runApp(TestApp());
TextField _textField1;
AlertDialog _fontPickerDialog;
class TestApp extends StatefulWidget {
@override
_TestAppState createState() => _TestAppState();
}
class _TestAppState extends State<TestApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test App',home: Scaffold(
backgroundColor: Colors.white,appBar: AppBar(
title: Center(
//for the centered title in the appbar
child: Text(
'TextField Test',),body: Stack(children: <Widget>[
///textfield
Container(
alignment: Alignment.center,child: RaisedButton(
child: Text('Click for TextField!'),onPressed: () {
setState(() {
textField();
});
})),Container(
child: _textField1,///fontpicker
Container(
alignment: Alignment.bottomLeft,child: RaisedButton(
child: Text('Choose Font'),onPressed: () {
setState(() {
fontPicker();
});
})),Container(
alignment: Alignment.center,child: _fontPickerDialog,])));
}
void textField() {
_textField1 = TextField(
style: TextStyle(
fontSize: 25,decoration: InputDecoration(
border: InputBorder.none,hintText: "Type Here...",hintStyle: TextStyle(
fontSize: 25,color: Colors.black,);
}
void fontPicker() {
_fontPickerDialog = AlertDialog(
title: const Text(
'Choose Font...',content: Container(
width: double.maxFinite,child: ListView(children: [
ListTile(
title: Text('Anton',style: GoogleFonts.getFont('Anton')),onTap: () {
setState(() {
_fontPickerDialog = null;
});
})
])));
}
}
解决方法
创建状态变量fontName
(可能默认为'Roboto'),并以TextField样式使用它:
GoogleFonts.getFont(fontName,fontSize: 25)
并在字体选择器的setState
中对其进行更新。