Flutter列表选择对话框插件list_picker_dialog_plus的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter列表选择对话框插件list_picker_dialog_plus的使用

获取开始

安装

pubspec.yaml 文件中添加以下依赖:

dependencies:
  list_picker_dialog_plus: <version_number>

简单文本列表选择器

以下是使用简单文本列表选择器的基本示例:

var item = await showTextListPicker(
    context: context,
    selectedItem: _selectedItem,
    findFn: (str) async => [
    "Apple",
    "Bannana",
    "Grapes",
    "Orrange",
    "Pineapple",
    ],
);
if (item != null) {
    setState(() {
    _selectedItem = item;
    });
}

高级选项列表选择器

以下是使用高级选项列表选择器的基本示例:

var item = await showListPicker(
    context: context,
    selectedItem: _selectedItem,
    findFn: (str) async => [
            "Apple",
            "Bannana",
            "Grapes",
            "Orrange",
            "Pineapple",
        ],
    filterFn: (dynamic item, str) =>
        item.toLowerCase().indexOf(str.toLowerCase()) >= 0,
    listItemFn: (item, position, focused, selected, onTap) =>
        ListTile(
            title: Text(
            item,
            style: TextStyle(
                color: selected ? Colors.blue : Colors.black87),
            ),
            tileColor: focused
                ? Color.fromARGB(10, 0, 0, 0)
                : Colors.transparent,
            onTap: onTap,
        ));
if (item != null) {
    setState(() {
    _selectedItem = item;
    });
}

完整示例代码

以下是完整的示例代码,展示如何在应用中使用上述功能:

import 'package:flutter/material.dart';
import 'package:list_picker_dialog_plus/list_picker_dialog_plus.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'List Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? _selectedItem;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('List Picker Demo'),
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              height: 60,
            ),
            ElevatedButton(
              child: Text("Simple List Picker"),
              onPressed: () async {
                var item = await showTextListPicker(
                  context: context,
                  selectedItem: _selectedItem,
                  findFn: (str) async => [
                    "Apple",
                    "Bannana",
                    "Grapes",
                    "Orrange",
                    "Pineapple",
                  ],
                );
                if (item != null) {
                  setState(() {
                    _selectedItem = item;
                  });
                }
              },
            ),
            SizedBox(
              height: 16,
            ),
            ElevatedButton(
              child: Text("Advance List Picker"),
              onPressed: () async {
                var item = await showListPicker(
                    context: context,
                    selectedItem: _selectedItem,
                    findFn: (str) async => [
                          "Apple",
                          "Bannana",
                          "Grapes",
                          "Orrange",
                          "Pineapple",
                        ],
                    filterFn: (dynamic item, str) =>
                        item.toLowerCase().indexOf(str.toLowerCase()) >= 0,
                    listItemFn: (String item, position, focused, selected,
                            onTap) =>
                        ListTile(
                          title: Text(
                            item,
                            style: TextStyle(
                                color: selected ? Colors.blue : Colors.black87),
                          ),
                          tileColor: focused
                              ? Color.fromARGB(10, 0, 0, 0)
                              : Colors.transparent,
                          onTap: onTap,
                        ));
                if (item != null) {
                  setState(() {
                    _selectedItem = item;
                  });
                }
              },
            ),
            SizedBox(
              height: 32,
            ),
            Text('Selected Item = $_selectedItem')
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

更多关于Flutter列表选择对话框插件list_picker_dialog_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter列表选择对话框插件list_picker_dialog_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用list_picker_dialog_plus插件来创建列表选择对话框的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了list_picker_dialog_plus依赖项:

dependencies:
  flutter:
    sdk: flutter
  list_picker_dialog_plus: ^x.y.z  # 请将 x.y.z 替换为最新版本号

然后运行flutter pub get来安装依赖项。

接下来,在你的Dart文件中,你可以使用ListPickerDialogPlus来创建列表选择对话框。下面是一个完整的示例:

import 'package:flutter/material.dart';
import 'package:list_picker_dialog_plus/list_picker_dialog_plus.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter List Picker Dialog Plus Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('List Picker Dialog Plus Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Value: ${selectedValue ?? 'None'}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                _showListPickerDialog();
              },
              child: Text('Show List Picker Dialog'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _showListPickerDialog() async {
    final List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
    final ListPickerDialogPlusResponse<String?>? response = await ListPickerDialogPlus.showDialog<String>(
      context: context,
      title: 'Select an Item',
      initialSelectedValue: selectedValue,
      items: items,
      searchEnabled: true,
      onConfirmed: (value) {
        setState(() {
          selectedValue = value;
        });
      },
      onCancelled: () {
        // Handle cancel event if needed
      },
    );

    // Handle response if needed, e.g., when the dialog is dismissed with a back button
    if (response != null) {
      if (response.confirmed) {
        print('Selected Value: ${response.selectedValues.first}');
      } else if (response.cancelled) {
        print('Dialog cancelled');
      }
    }
  }
}

代码解释:

  1. 依赖导入:导入flutter/material.dartlist_picker_dialog_plus/list_picker_dialog_plus.dart
  2. 应用入口:在main.dart文件中定义MyAppMyHomePage
  3. 状态管理:在_MyHomePageState中定义selectedValue来存储选中的值。
  4. UI布局
    • 使用AppBar创建一个应用栏。
    • 使用Column布局显示当前选中的值和按钮。
  5. 对话框显示
    • ElevatedButtononPressed方法调用_showListPickerDialog
    • _showListPickerDialog方法使用ListPickerDialogPlus.showDialog来显示列表选择对话框。
    • 设置对话框的标题、初始选中值、列表项以及搜索功能。
    • 使用onConfirmed回调更新selectedValue

这个示例展示了如何使用list_picker_dialog_plus插件在Flutter应用中创建和显示一个列表选择对话框,并处理用户的选择和取消操作。

回到顶部