DEV Community

Cover image for Syncfusion Data Grid Flutter
Muhammad Manan
Muhammad Manan

Posted on

Syncfusion Data Grid Flutter

First things first before doing anything.
Add dependency

Add the Syncfusion Flutter DataGrid dependency to your pubspec.yaml file.

dependencies:
    syncfusion_flutter_datagrid: ^latest_version
Enter fullscreen mode Exit fullscreen mode

Get packages

Run the following command to get the required packages.

$ flutter pub get
Enter fullscreen mode Exit fullscreen mode

Import package

Import the following package in your Dart code.

DART

import 'package:syncfusion_flutter_datagrid/datagrid.dart';
Enter fullscreen mode Exit fullscreen mode

Use whatever state management you want to use. I prefer provider so i am using that.

For this add the Provider dependency to your pubspec.yaml file.

dependencies:
    provider: ^latest_version
Enter fullscreen mode Exit fullscreen mode

Initialize the provider files in main.dart

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: multiProvider,
      child: MaterialApp(
        builder: (context, child) => MediaQuery(
          data: MediaQuery.of(context).copyWith(
            alwaysUse24HourFormat: true,
          ),
          child: child!,
        ),
        debugShowCheckedModeBanner: false,
        title: 'Data Grid',
        home: const Dashboard(),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

I prefer a global file for holding all providers, So make multi_provider.dart file and add the following code:


import 'package:provider/provider.dart';
import '../screens/dashboard/controller/dash_controller.dart';

var multiProvider = [

  /// DashProvider ///
  ChangeNotifierProvider<DashProvider>(
    create: (_) => DashProvider(),
    lazy: true,
  ),

];

Enter fullscreen mode Exit fullscreen mode

After that we need to add our variables to dashboard provider, i am using a rest api for the data u can use firebase as well.
Add the following code to provider file:


// Initialize ur api service class
ApiService apiService = ApiService();

final GlobalKey<SfDataGridState> key = GlobalKey<SfDataGridState>();

bool _isLoading = false;
bool get isLoading => _isLoading;

//Add u header columns
  List<GridColumn> grid = [
    GridColumn(
        columnName: 'ID',
        label: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            alignment: Alignment.center,
            child:  Text(
              'Vehicle',
              style: TextStyle(color: white),
              overflow: TextOverflow.ellipsis,
            ))),
  ];

  late ReportDetailData reportDetailData;
  List<DataModel> _data = [];
  List<DataModel> get data => _data;

  Future<void> getData(BuildContext context) async {
    _isLoading = true;
    notifyListeners();
    apiService.getData().then((response) {
      List<dynamic> data = json.decode(response.body);
      if (response.statusCode == 200 && data.toString() != "[]") {
        _data = data.map((data) => DataModel.fromJson(data)).toList();

        reportDetailData = ReportDetailData(data: _data);
        _isLoading = false;
        notifyListeners();
      } else if (response.statusCode == 200 && data.toString() == "[]") {
        _isLoading = false;
        notifyListeners();
      } else {
        _isLoading = false;
        notifyListeners();
      }
    });
  }
Enter fullscreen mode Exit fullscreen mode

After doing all that come to ur dashboard.dart file and call the api on initState.

Now Add the following code to initState:

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      context.read<DashProvider>().getData(context);
    });
  }
Enter fullscreen mode Exit fullscreen mode

For the widget part add the following code:

// Add this to the Scaffold body
context.watch<DashProvider>().isLoading
            ? const Align(
                alignment: Alignment.center,
                child: Text("Loading....),
              )
            : SfDataGridTheme(
                    data: SfDataGridThemeData(headerColor: Colors.black),
                    child: SfDataGrid(

                        gridLinesVisibility: GridLinesVisibility.both,
                        rowsPerPage: 20,
                        key: context.read<DashProvider>().key,
                        source: context
                            .read<DashProvider>()
                            .reportDetailData,
                        allowSorting: true,
                        columnWidthMode: ColumnWidthMode.fill,
                        selectionMode: SelectionMode.multiple,
                        navigationMode: GridNavigationMode.cell,
                        columns: context.read<DashProvider>().grid),
                  )
Enter fullscreen mode Exit fullscreen mode

And Finally don't forget to add the reportDetailData class..

Add the following code:

class ReportDetailData extends DataGridSource {
  /// Creates the employee data source class with required details.
  ReportDetailData({required List<DataModel> data}) {
    _employeeData = data.map<DataGridRow>((DataModel e) {
      return DataGridRow(cells: <DataGridCell>[
        DataGridCell<String>(
            columnName: 'ID',
            value: e.id.toString() == "null" ? "N/A" : e.id.toString()),

    }).toList();
  }

  List<DataGridRow> _employeeData = <DataGridRow>[];

  @override
  List<DataGridRow> get rows => _employeeData;

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((DataGridCell cell) {
      return Container(
        alignment: Alignment.center,
        child: Text(
          cell.value.toString(),
          style: TextStyle(fontSize: 15),
          textAlign: TextAlign.center,
        ),
      );
    }).toList());
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all u need to do run the app by using the following command.

$flutter run
Enter fullscreen mode Exit fullscreen mode

Hurray u finally made a data grid using Syncfusion package flutter.

Final Result:
Image description

Keep sure to check out my packages and leave a suggestion:
https://pub.dev/packages/fancy_button_new
https://pub.dev/packages/fancy_field_new

Top comments (0)