TL;DR: Learn how to build a smart, predictive DataGrid in Flutter using Gemini AI. This guide shows how to integrate generative AI to compute student GPA, grades, and display the results in real-time within a dynamic Flutter interface.
AI is reshaping app development, and now, you can use it to bring intelligence directly into your Flutter apps. In this blog, you’ll learn how to integrate Gemini AI with Syncfusion® Flutter DataGrid to create a smart grid that automatically computes and displays student performance metrics like GPA and grades.
From setting up the AI model to feeding it student data and updating the UI, we’ll walk through each step with code examples you can try right away.
Let’s dive in and explore!
Building your app environment
Step 1: Connect Gemini AI with your Flutter App
First, the Gemini OpenAI creates an instance of a generative AI model with the specified version (gemini-1.5-flash-latest). The apiKey is required to authenticate requests to the AI service. The method _model.startChat() initializes a chat session, allowing the application to facilitate interactive, AI-driven conversations. This setup enables real-time engagement with AI capabilities directly within the app.
Refer to the following code example.
@override
void initState() {
super.initState();
_studentDetails = getStudentData();
_model = GenerativeModel(
model: 'gemini-1.5-flash-latest',
apiKey: 'YOUR-KEY',
);
_chat = _model.startChat();
_studentDataSource = StudentDataSource(student: _studentDetails, context: context);
// Initialize the animation controller.
_controller = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
)..repeat(reverse: true);
// Define the animation.
_animation = Tween(begin: 0.8, end: 1).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
);
}
Step 2: Generate prompts for Student prediction
Secondly, the _generatePrompt() method generates a comprehensive prompt string tailored for a generative AI model. This prompt provides detailed instructions and data for producing a structured JSON response based on student information and calculation rules. It ensures clarity and structure, enabling the AI model to deliver accurate and well-formatted outputs, including computed properties such as finalYearGPA, totalGPA, and totalGrade for each student.
Refer to the following code example.
String _generatePrompt() {
String prompt = 'Provide the results in strict JSON format only.';
prompt += 'Each student should have the following properties: ';
prompt +=
'`studentID` (int), `finalYearGPA` (Double), `totalGPA` (Double), and `totalGrade` (String). ';
prompt += 'Here is the data and calculation criteria:\n\n';
prompt +=
'1. `finalYearGPA` should be equal to the GPA from the third year (thirdYearGPA) only.\n';
prompt +=
"2. `totalGPA` should be the average of all three years' GPAs (first, second, and third years) with one decimal digit.\n";
prompt +=
'3. `totalGrade` should be assigned based on `totalGPA` following standard grading. Updated the grade based on following details, 0 - 2.5 = F, 2.6 - 2.9 = C, 3.0 - 3.4 = B, 3.5 - 3.9 = B+, 4.0 - 4.4 = A, 4.5 - 5 = A+.\n\n';
final String studentJson =
jsonEncode(_studentDetails.map((student) => student.toJson()).toList());
prompt += studentJson;
prompt += '\nRespond in this JSON format:\n';
return prompt;
}
Step 3: Display Smart Data in Flutter DataGrid
The DataGrid widget provides an interactive interface for displaying a data grid with student data and triggering an AI-driven operation via the “AI” button. It also shows a loading indicator during asynchronous operations. This design emphasizes usability and visual appeal, leveraging animations and responsive UI elements.
Refer to the following code example.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(60),
child: AppBar(
title: const Center(
child: Text(
'Predictive Data Entry',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
),
automaticallyImplyLeading: false,
actions: [
Align(
alignment: Alignment.topCenter,
child: AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget? child) {
return Container(
padding: const EdgeInsets.fromLTRB(0, 10, 10, 0),
child: Transform.scale(
scale: _isPressed ? 1 : _animation.value,
child: FloatingActionButton(
mini: true,
backgroundColor: Theme.of(context).primaryColor,
onPressed: () {
if (!_isPressed) {
_sendChatMessage(_generatePrompt());
_isPressed = true;
}
},
child: Text(
'AI',
style: TextStyle(color: Colors.white),
)),
),
);
},
),
),
],
),
),
body: Stack(
children: [
SfDataGrid(
source: _studentDataSource,
columns: _studentDataSource._columns,
columnWidthMode: ColumnWidthMode.fill,
),
if (_isLoading)
const Center(
child: CircularProgressIndicator(),
),
],
),
);
}
Step 4: Converting AI response to DataGrid Source
Finally, the code defines the _convertAIResponseToStudents method, which handles an AI-generated string response, extracts student details, and updates the relevant rows in a DataGrid. This asynchronous method (Future<List<StudentDetails>>) transforms the AI-generated JSON data into a list of StudentDetails objects. It synchronizes the updated data with the DataGrid (_studentDataSource), ensuring the grid accurately reflects the changes.
Refer to the following code example.
Future _convertAIResponseToStudents(String? data) async {
if (data != null) {
data = data.replaceAll(RegExp(r'^```json|```$|\s*```\s*'), '').trim();
if (data.startsWith('[')) {
final parsedResponse = jsonDecode(data);
if (parsedResponse is List) {
int rowIndex = 0;
for (final student in parsedResponse) {
final int studentID = student['studentID'];
final double finalYearGPA = student['finalYearGPA'];
final double totalGPA = (student['totalGPA'] as num).toDouble();
final String totalGrade = student['totalGrade'];
for (final student in _studentDetails) {
if (student.studentID == studentID) {
student.finalYearGPA = finalYearGPA;
_studentDataSource.updateDataRow(rowIndex, student);
_studentDataSource.updateDataGridSource(
rowColumnIndex: RowColumnIndex(rowIndex, 5),
);
student.totalGPA = totalGPA;
_studentDataSource.updateDataRow(rowIndex, student);
_studentDataSource.updateDataGridSource(
rowColumnIndex: RowColumnIndex(rowIndex, 6),
);
student.totalGrade = totalGrade;
_studentDataSource.updateDataRow(rowIndex, student);
_studentDataSource.updateDataGridSource(
rowColumnIndex: RowColumnIndex(rowIndex, 7),
);
rowIndex++;
await Future.delayed(const Duration(milliseconds: 150));
break;
}
}
_studentDataSource.notifyListeners();
}
}
}
}
return _studentDetails;
}
References
For additional information, please refer to the GitHub demo.
Unlock the power of Syncfusion’s highly customizable Flutter widgets.
Conclusion
Bringing AI into your Flutter app doesn’t have to be complex. With just a few steps, you can connect a generative AI model like Gemini to your DataGrid and unlock powerful predictive capabilities such as automatically calculating student GPAs and grades. Whether you’re building educational tools or data-heavy dashboards, AI-driven interfaces can simplify logic, reduce manual work, and enhance user experience.
Ready to take your Flutter app to the next level with AI? Start experimenting today, the future is predictive.
For more details, don’t forget to check our Release Notes and What’s New pages. We value your feedback, so feel free to share your thoughts in the comments below!
If you’re a current Syncfusion® customer, you can download the latest updates from the license and downloads page. Not a customer yet? Try our full suite of features with a 30-day free trial, no commitment required!
You can also share your feedback or feature requests through our support forum, support portal, or feedback portal. We’re always here to assist you!