DEV Community

Cover image for Syncfusion Data Grid Flutter
Muhammad Manan
Muhammad Manan

Posted on

4

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

📊 A side-by-side product comparison between Sentry and Crashlytics

A free guide pointing out the differences between Sentry and Crashlytics, that’s it. See which is best for your mobile crash reporting needs.

See Comparison

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay