His six off the first delivery of the final over, bowled by pacer Nuwan Kulasekara, gave Pakistan a 1-0 lead in the two-match series.
Afridi hit three sixes and two boundaries in an unbeaten 20-ball 39 as Pakistan, who needed six from the final over, overcame a tough challenge from the world No 1 side.
Set a challenging 146, Pakistan lost Ahmed Shehzad (four) in the third over, but Mohammad Hafeez (32) and Sharjeel Khan (34) steadied the innings through their 57-run second wicket stand before losing three wickets in the space of seven runs.
Sharjeel holed out after hitting three fours off 31 balls while Hafeez, who hit two fours and a six in his 27-ball knock, fell leg before and Umar Akmal was run out for five.
It was left to Afridi to see Pakistan through.
Criticised for his recent poor batting form, he hit two towering sixes in Kulasekara's 16th over to give Pakistan a sniff of victory.
When on 23, Afridi also became the first player to score 1,000 runs and take 50 wickets in all Twenty20 cricket.
He has 73 wickets in 69 matches.
Sent in to bat, Sri Lanka’s batsmen did not capitalise on good starts. It was a fifth-wicket stand of 58 between Mathews (50) and Lahiru Thirimanne (23 not out) that enabled the team to post 145-5 in 20 overs.
Mathews hit five boundaries and a six off 34 balls before holing out in the last over. He hit pacer Bilawal Bhatti for three boundaries in one over and then dispatched left-arm paceman Sohail Tanvir to the long-on ropes to reach his fifty off 32 balls.
Experienced opener Tillakaratne Dilshan was the first to depart, in the second over, after scoring just seven.
Kusal Perera (15) and skipper Dinesh Chandimal (22) then added 32 for the second wicket but off-spinner Saeed Ajmal (2-35) put the brakes
Kumar Sangakkara scored 21.
Pakistan handed an international debut to 19-year-old Usman Shinwari. The left-arm pacer was drafted into the team as late as on Tuesday but the youngster from the troubled Kahyber Pakhtunkhwa province bowled only one over, which cost nine runs.
Tanvir finished with 2-32 while leg-spinner Afridi took 1-20 in his four overs.
The second match will also be played in Dubai on Friday. The two teams also play five one-day internationals and three Tests.
Image: Shahid Afridi celebrates after clinching victory for Pakistan at the Dubai Sports City Cricket Stadium
Photograph: Francois Nel/Getty Images
Pakistan axe Malik, Razzaq for Sri Lanka series
Pakistan paceman Irfan ruled out of South Africa tour
Afridi describes Yousuf, Akhtar as 'heckle and jeckle'
South Africa secure narrow win over Pakistan after rain
South Africa seal series win after rush of Pakistan wickets