Flutter芯片输入插件flutter_chips_input的使用
Flutter芯片输入插件flutter_chips_input的使用
安装
首先,你需要在pubspec.yaml
文件中添加flutter_chips_input
依赖:
dependencies:
flutter_chips_input: ^0.6.0
然后运行flutter pub get
来获取该库。
导入
在你的 Dart 文件中导入 flutter_chips_input
库:
import 'package:flutter_chips_input/flutter_chips_input.dart';
示例
下面是一个完整的示例,展示了如何使用 flutter_chips_input
插件。
import 'package:flutter/material.dart';
import 'package:flutter_chips_input/flutter_chips_input.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Chips Input',
theme: ThemeData(
primarySwatch: Colors.blue,
// brightness: Brightness.dark,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _chipKey = GlobalKey<ChipsInputState>();
[@override](/user/override)
Widget build(BuildContext context) {
const mockResults = [
AppProfile('John Doe', 'jdoe@flutter.io',
'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg'),
AppProfile('Paul', 'paul@google.com',
'https://mbtskoudsalg.com/images/person-stock-image-png.png'),
AppProfile('Fred', 'fred@google.com',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Brian', 'brian@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('John', 'john@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Thomas', 'thomas@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Nelly', 'nelly@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Marie', 'marie@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Charlie', 'charlie@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Diana', 'diana@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Ernie', 'ernie@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
AppProfile('Gina', 'fred@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'),
];
return Scaffold(
appBar: AppBar(title: const Text('Flutter Chips Input Example')),
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.all(20),
child: SingleChildScrollView(
child: Column(
children: [
ChipsInput(
key: _chipKey,
// initialValue: [
// AppProfile('John Doe', 'jdoe@flutter.io',
// 'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg'),
// ],
// autofocus: true,
// allowChipEditing: true,
keyboardAppearance: Brightness.dark,
textCapitalization: TextCapitalization.words,
// enabled: false,
// maxChips: 5,
textStyle: const TextStyle(
height: 1.5, fontFamily: 'Roboto', fontSize: 16),
decoration: const InputDecoration(
// prefixIcon: Icon(Icons.search),
// hintText: formControl.hint,
labelText: 'Select People',
// enabled: false,
// errorText: field.errorText,
),
findSuggestions: (String query) {
if (query.isNotEmpty) {
var lowercaseQuery = query.toLowerCase();
return mockResults.where((profile) {
return profile.name
.toLowerCase()
.contains(query.toLowerCase()) ||
profile.email
.toLowerCase()
.contains(query.toLowerCase());
}).toList(growable: false)
..sort((a, b) => a.name
.toLowerCase()
.indexOf(lowercaseQuery)
.compareTo(
b.name.toLowerCase().indexOf(lowercaseQuery)));
}
// return <AppProfile>[];
return mockResults;
},
onChanged: (data) {
// print(data);
},
chipBuilder: (context, state, dynamic profile) {
return InputChip(
key: ObjectKey(profile),
label: Text(profile.name),
avatar: CircleAvatar(
backgroundImage: NetworkImage(profile.imageUrl),
),
onDeleted: () => state.deleteChip(profile),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
},
suggestionBuilder: (context, state, dynamic profile) {
return ListTile(
key: ObjectKey(profile),
leading: CircleAvatar(
backgroundImage: NetworkImage(profile.imageUrl),
),
title: Text(profile.name),
subtitle: Text(profile.email),
onTap: () => state.selectSuggestion(profile),
);
},
),
const TextField(),
ElevatedButton(
onPressed: () {
_chipKey.currentState!.selectSuggestion(const AppProfile(
'Gina',
'fred@flutter.io',
'https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png'));
},
child: const Text('Add Chip'),
),
],
),
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class AppProfile {
final String name;
final String email;
final String imageUrl;
const AppProfile(this.name, this.email, this.imageUrl);
[@override](/user/override)
bool operator ==(Object other) =>
identical(this, other) ||
other is AppProfile &&
runtimeType == other.runtimeType &&
name == other.name;
[@override](/user/override)
int get hashCode => name.hashCode;
[@override](/user/override)
String toString() {
return name;
}
}
更多关于Flutter芯片输入插件flutter_chips_input的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter芯片输入插件flutter_chips_input的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用flutter_chips_input
插件的一个简单示例。这个插件允许你创建一个类似于聊天应用中的标签输入字段。
首先,确保你的Flutter项目已经创建,并且你已经在pubspec.yaml
文件中添加了flutter_chips_input
依赖项:
dependencies:
flutter:
sdk: flutter
flutter_chips_input: ^2.0.0 # 请检查最新版本号
然后运行flutter pub get
来获取依赖项。
接下来,在你的Flutter项目中使用flutter_chips_input
。以下是一个完整的示例,展示如何在你的应用中集成这个插件:
import 'package:flutter/material.dart';
import 'package:flutter_chips_input/flutter_chips_input.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Chips Input Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChipsInputExample(),
);
}
}
class ChipsInputExample extends StatefulWidget {
@override
_ChipsInputExampleState createState() => _ChipsInputExampleState();
}
class _ChipsInputExampleState extends State<ChipsInputExample> {
List<String> chips = [];
void handleChipSubmission(Chip chip) {
setState(() {
chips.add(chip.label);
});
}
void handleChipDeletion(String deletedChip) {
setState(() {
chips.remove(deletedChip);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Chips Input Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Selected Chips:',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: List.generate(
chips.length,
(index) => Chip(
label: Text(chips[index]),
onDeleted: () => handleChipDeletion(chips[index]),
),
),
),
SizedBox(height: 24),
ChipsInput<String>(
initialValue: chips,
findSuggestions: (String query) {
// 这里你可以添加你的建议逻辑,例如从API获取建议
List<String> suggestions = [
'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry',
'Fig', 'Grape', 'Honeydew', 'Kiwi', 'Lemon'
].where((suggestion) {
return suggestion.toLowerCase().contains(query.toLowerCase());
}).toList();
return Future.value(suggestions);
},
chipBuilder: (Chip chip) {
return Chip(
label: Text(chip),
avatar: CircleAvatar(
backgroundColor: Colors.grey.shade300,
child: Text(chip[0].toUpperCase()),
),
onDeleted: () => handleChipDeletion(chip),
);
},
onSubmitted: (Chip chip) => handleChipSubmission(chip),
decoration: InputDecoration(
prefixIcon: Icon(Icons.label),
border: OutlineInputBorder(),
labelText: 'Add a chip',
hintText: 'Start typing...',
),
),
],
),
),
);
}
}
在这个示例中:
- 我们创建了一个
ChipsInputExample
类,它使用StatefulWidget
来管理状态。 - 在
_ChipsInputExampleState
类中,我们维护了一个chips
列表来存储已选择的芯片。 handleChipSubmission
方法用于在提交新芯片时更新chips
列表。handleChipDeletion
方法用于在删除芯片时更新chips
列表。ChipsInput
小部件用于显示和编辑芯片输入字段。findSuggestions
方法提供了一个简单的基于字符串匹配的建议列表。chipBuilder
方法定义了每个芯片的外观,包括标签和头像。
这个示例展示了如何基本使用flutter_chips_input
插件,并可以根据你的需求进行扩展和定制。