chartjs_flutter 1.0.0
chartjs_flutter: ^1.0.0 copied to clipboard
A Flutter package for rendering Chart.js charts across web and mobile platforms.
import 'dart:math';
import 'package:chartjs_flutter/chartjs_flutter.dart';
import 'package:flutter/material.dart';
/// Example application demonstrating ChartJS Flutter usage.
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
/// Main application widget.
class MyApp extends StatelessWidget {
/// Creates the main application widget.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ChartJS Flutter Example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true,
),
home: const DemoPage(),
);
}
}
/// Demo page showing Chart.js widget in action.
class DemoPage extends StatefulWidget {
/// Creates the demo page.
const DemoPage({super.key});
@override
State<DemoPage> createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
late Map<String, dynamic> _chartConfig;
@override
void initState() {
super.initState();
_chartConfig = _buildLineChartConfig();
}
/// Builds initial line chart configuration.
Map<String, dynamic> _buildLineChartConfig() {
return {
'type': 'line',
'data': {
'labels': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'datasets': [
{
'label': 'Sales',
'data': [65, 59, 80, 81, 56, 55],
'borderColor': 'rgb(0,128,128)',
'tension': 0.1,
},
{
'label': 'Expenses',
'data': [28, 48, 40, 19, 86, 27],
'borderColor': 'rgb(255,0,0)',
'tension': 0.4,
'fill': true,
},
],
},
'options': {
'responsive': true,
'maintainAspectRatio': false,
},
};
}
/// Updates chart with random data to demonstrate dynamic updates.
void _updateChartData() {
final random = Random();
setState(() {
_chartConfig = {
'type': 'line',
'data': {
'labels': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
'datasets': [
{
'label': 'CPU Usage',
'data': List.generate(6, (_) => random.nextInt(100)),
'borderColor': 'rgb(128,0,128)',
'tension': 0.3,
},
],
},
'options': {
'responsive': true,
'maintainAspectRatio': false,
},
};
});
}
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height * 0.5;
return Scaffold(
appBar: AppBar(title: const Text('ChartJS Flutter Demo')),
body: Center(
child: SizedBox(
height: height,
width: MediaQuery.of(context).size.width * 0.95,
child: Card(
elevation: 4,
child: Padding(
padding: const EdgeInsets.all(8),
child: ChartJsWidget(chartConfig: _chartConfig),
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _updateChartData,
tooltip: 'Update Data',
child: const Icon(Icons.refresh),
),
);
}
}