如何创建一个在用户输入时更改字体和颜色的TextField



我对Flutter和用Dart语言写作还很陌生。我正在尝试创建一个在用户输入时更改颜色和字体族的TextField。到目前为止,我有一个按钮可以创建一个新的TextField。我为字体创建了一个对话框。我只是不知道如何保存字体对话框中的用户输入,并将其链接到TextField。

这是一张带有TextField 的照片

这是我可以选择字体的地方

问题是我不知道如何链接字体,用户会选择实际更改文本字体。

有人能帮我吗!

这是我的代码:

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)

并在字体选择器中的CCD_ 2中对其进行更新。

最新更新